package com.taichuan.selfcheck.db;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;


import com.taichuan.selfcheck.entity.greendao.dao.DaoMaster;
import com.taichuan.selfcheck.entity.greendao.dao.DaoSession;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

/**
 * 该类主要用于 封装greenDao 的管理核心类
 *
 * @author CamelLuo
 * @version 2019/11/15
 */
public class DaoManager {
    private static final String TAG = DaoManager.class.getSimpleName();

    public static final String DB_NAME = "TcSelfCheck.db";//数据库名称
    private static DaoManager mDaoManager;
    private GreenDaoUpgradeHelper mHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private Context applicationContext;

    private DaoManager() {
    }

    /**
     * 初始化数据库管理类
     * @param applicationContext
     */
    public void init(Context applicationContext){
        this.applicationContext = applicationContext;
    }

    /**
     * 使用单例模式获得操作数据库的对象
     *
     * @return
     */
    public static DaoManager getInstance() {
        if (mDaoManager == null) {
            synchronized (DaoManager.class) {
                if (mDaoManager == null) {
                    mDaoManager = new DaoManager();
                }
            }
        }
        return mDaoManager;
    }

    /**
     * 获取DaoSession
     *
     * @return
     */
    public synchronized DaoSession getDaoSession() {
        if (null == mDaoSession) {
            mDaoSession = getDaoMaster().newSession();
        }
        return mDaoSession;
    }

    /**
     * 设置debug模式开启或关闭，默认关闭
     *
     * @param flag
     */
    public  void setDebug(boolean flag) {
        QueryBuilder.LOG_SQL = flag;
        QueryBuilder.LOG_VALUES = flag;
    }

    /**
     * 关闭数据库
     */
    public synchronized void closeDataBase() {
        closeHelper();
        closeDaoSession();
    }

    /**
     * 判断数据库是否存在，如果不存在则创建
     *
     * @return
     */
    private DaoMaster getDaoMaster() {
        if (null == mDaoMaster) {
            //使用 GreenDaoUpgradeHelper 进行数据库创建类
            mHelper = new GreenDaoUpgradeHelper(applicationContext, DB_NAME, null);
            mDaoMaster = new DaoMaster(mHelper.getWritableDb());
        }
        return mDaoMaster;
    }

    private void closeDaoSession() {
        if (null != mDaoSession) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }

    private void closeHelper() {
        if (mHelper != null) {
            mHelper.close();
            mHelper = null;
        }
    }

    /**
     * 定义一个方法用于直接通过Sql语句进行 表中某些字段的 DISTINCT 去重查询
     * sql语句样例： SELECT DISTINCT Colums名1,Colums名2 * FROM 表名 WHERE语句
     * @param tableEntityName 需要查询的表名
     * @param whereCondition Where查询条件
     * @param columns 需要查重过滤的字段
     * @return 查询结果Cursor游标对象
     */
    public Cursor queryDistinctForColums(String tableEntityName,WhereCondition whereCondition,String... columns){
        StringBuilder result = new StringBuilder();
        //添加去重过滤
        result.append("SELECT DISTINCT ");

        //添加需要去重过滤的 Colums 字段
        if (columns != null) {
            result.append(columns[0]);
            for (int i = 1; i < columns.length; i++) {
                result.append("," + columns[i]);
            }
        } else {
            result.append("* ");
        }

        result.append(" FROM ").append(tableEntityName);

        if (whereCondition != null){
            //拼接Where查询
            result.append(" WHERE ");
            whereCondition.appendTo(result,null);
        }

        //移除引号
        String endSql = result.toString();  //.replace("\"", "")

        Log.e(TAG, "queryDistinctForColums: 最终拼接的sql语句为：  " + endSql);

        Cursor cursor = DaoManager.getInstance().getDaoSession().getDatabase().rawQuery(endSql, null);
        return cursor;
    }
}
